The jquery plug in implements the automatic height of the multi line text box [textarea]

  • 2020-05-10 17:42:57
  • OfStack

Implementation functions:

1/ automatically increases the height of a row when textarea wraps
2/ when textarea removes 1 line, it automatically reduces 1 line and is highly dependent: jquery.xxx.js needs to use a similar feature for work but finds it inconvenient to import other files using the plug-in, so it writes 1

textarea jquery plug-in


<div class="form-group">
    <label class="col-sm-3 control-label no-padding-right" for="form-field-5"> content </label>
    <div class="col-sm-9">
        <textarea class="col-sm-8" id="form-field-5" placeholder=" Please enter the content ..."></textarea>
    </div>
</div>


jQuery.extend({
    textareaAutosize_dc: function() {
        $("textarea").on("keyup", function(e) {
            var currentEnterCount = $(this).val().split("\n").length;
            var lineHeight = Number($(this).css("line-height").replace("px", ""));
            var enterCount = $(this).attr("enterCount");
            if (currentEnterCount < enterCount && enterCount != undefined) {
                // Each row is subtracted from the fixed row height
                $(this).height($(this).height() - lineHeight);
            } else if (currentEnterCount > enterCount) {
                // Add a fixed row height to each row
                $(this).height($(this).height() + lineHeight);
                $(this).attr("enterCount", currentEnterCount);
            }
            // Records the current row height
            $(this).attr("enterCount", currentEnterCount);
        });
    }
});
// Call auto height
$.textareaAutosize_dc();

That's all for this article, I hope you enjoy it.


Related articles: